package com.example.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class DownloadService extends Service {
    public static final String TAG = DownloadService.class.getSimpleName();
    private int progress = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()被调用");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand()被调用");
        return START_REDELIVER_INTENT;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind()被调用");
        return new MyBinder();
    }


    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind()被调用");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()被调用");
    }

    // 模拟下载任务，每秒钟更新一次
    public void startDownload() {
        Log.d(TAG, "startDownload()被调用");
        progress = 0;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progress < 100) {
                    progress += 5;
                    // 进度发生变化时通知MainActivity
                    if(onProgressListener != null){
                        onProgressListener.onProgress(progress);
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //
    class MyBinder extends Binder {
        public DownloadService getService() {
            return DownloadService.this;
        }
    }

    // 注册回调接口的方法
    private OnProgressListener onProgressListener;
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }
    // 更新进度的回调接口
    public interface OnProgressListener {
        void onProgress(int progress);
    }
}
